//
//  AppDelegate.m
//  iCarStyle
//
//  Created by liunian on 13-9-5.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "AppDelegate.h"
#import "MKNavigationController.h"
#import "DataEnvironment.h"
#import "MBPullDownController.h"
#import "ArticleManager.h"
#import "UMSocial.h"
#import "WXApi.h"
#import "MobClick.h"
#import "ALAlertBanner.h"
#import "NewsEntity.h"
#import "RootSideController.h"

static NSString * const kRecipesStoreName = @"iCarStyle.sqlite";

@implementation AppDelegate

- (void)dealloc{
    MKRemoveNetworkStatusObserver(self);
}
- (void)hideTabbar:(BOOL)isHidde{
    [self.rootViewController hideTabbar:isHidde];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    MKAddNetworkStatusObserver(self);
    //向微信注册
    [WXApi registerApp:kWeChatAPPID];
    //设置友盟appkey
    [UMSocialData setAppKey:kUmengAppKey];
    
    //如果你要支持不同的屏幕方向，需要这样设置，否则在iPhone只支持一个竖屏方向
    [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskPortrait];
    [MobClick startWithAppkey:kUmengAppKey reportPolicy:BATCH channelId:kUmeng91storeChannelId];
    [self copyDefaultStoreIfNecessary];

    [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:kRecipesStoreName];
    application.applicationIconBadgeNumber = 0;
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];

    RootSideController *rootViewController = [RootSideController rootViewController];
    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];
    UIColor *navigationTextColor = [UIColor whiteColor];

    self.window.tintColor = navigationTextColor;
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : navigationTextColor}];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application{

}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [MobClick checkUpdate:@"有新版本更新啦！" cancelButtonTitle:@"我爱怀旧" otherButtonTitles:@"我爱潮流"];
    [UMSocialSnsService  applicationDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}
/**
 这里处理新浪微博SSO授权之后跳转回来，和微信分享完成之后跳转回来
 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

/**
 这里处理新浪微博SSO授权进入新浪微博客户端后进入后台，再返回原来应用
 */

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"注册推送失败");
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    application.applicationIconBadgeNumber = 0;
}

#pragma mark - MKEnvObserverNetworkStatusProtocol
- (void)mkEnvObserverNetworkStatusDidChangedFromStatus:(NetworkStatus)fromStatus toStatus:(NetworkStatus)toStatus{
    if (toStatus == kNotReachable) {
        ALAlertBannerStyle randomStyle = ALAlertBannerStyleFailure;
        ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
        ALAlertBanner *banner = [ALAlertBanner alertBannerForView:self.window style:randomStyle position:position title:@"错误" subtitle:@"目前无网络连接,只能查看部分离线内容!" tappedBlock:^(ALAlertBanner *alertBanner) {
            NSLog(@"tapped!");
            [alertBanner hide];
        }];
        banner.secondsToShow = 2;
        banner.showAnimationDuration = 0.25;
        banner.hideAnimationDuration = 0.20;
        [banner show];
        
    }else{
        ALAlertBannerStyle randomStyle = ALAlertBannerStyleSuccess;
        ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
        ALAlertBanner *banner = [ALAlertBanner alertBannerForView:self.window style:randomStyle position:position title:@"提示" subtitle:@"网络已连接，可以正常使用!" tappedBlock:^(ALAlertBanner *alertBanner) {
            NSLog(@"tapped!");
            [alertBanner hide];
        }];
        banner.secondsToShow = 2;
        banner.showAnimationDuration = 0.25;
        banner.hideAnimationDuration = 0.20;
        [banner show];
    }
}

#pragma mark APNs
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    ALAlertBanner *banner = [ALAlertBanner alertBannerForView:self.window style:ALAlertBannerStyleNotify position:ALAlertBannerPositionTop title:@"消息推送" subtitle:content tappedBlock:^(ALAlertBanner *alertBanner) {
        [alertBanner hide];
    }];
    banner.secondsToShow = 2;
    banner.showAnimationDuration = 0.25;
    banner.hideAnimationDuration = 0.20;
    [banner show];
}

#pragma mark - Core Data stack
- (void) copyDefaultStoreIfNecessary;
{
	NSFileManager *fileManager = [NSFileManager defaultManager];

    NSURL *storeURL = [NSPersistentStore MR_urlForStoreName:kRecipesStoreName];

	// If the expected store doesn't exist, copy the default store.
	if (![fileManager fileExistsAtPath:[storeURL path]])
        {
		NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:[kRecipesStoreName stringByDeletingPathExtension] ofType:[kRecipesStoreName pathExtension]];

		if (defaultStorePath)
            {
            NSError *error;
			BOOL success = [fileManager copyItemAtPath:defaultStorePath toPath:[storeURL path] error:&error];
            if (!success)
                {
                NSLog(@"Failed to install default recipe store");
                }
            }
        }
}

#pragma mark getter
- (RootViewController *)rootViewController{
    if (!_rootViewController) {
        _rootViewController = [[RootViewController alloc] init];
    }
    return _rootViewController;
}

- (MainViewController *)mainViewController{
    if (!_mainViewController) {
        _mainViewController = [[MainViewController alloc] init];
    }
    return _mainViewController;
}

- (NewsViewController *)newsViewController{
    if (!_newsViewController) {
        _newsViewController = [[NewsViewController alloc] init];
    }
    return _newsViewController;
}
@end
